from datetime import datetime, timedelta
from fastapi import FastAPI, HTTPException
import uvicorn
# 设置密钥
from jwt import jwt
SECRET_KEY = "081JlWpx1qlMLguHCDSNqKaZqrY7WnhwdKW7P43mgZs="
# 设置加密算法
ALGORITHM = "HS256"

# 创建app对象
app = FastAPI()


# 创建令牌函数
def create_access_token(data: dict):
    # 创建一个副本
    to_encode = data.copy()
    # 设置令牌有效期
    expire = datetime.utcnow() + timedelta(minutes=15)
    # 更新字典
    to_encode.update({"exp": expire})
    # 对jwt进行编码
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    # 返回生成的令牌
    return encoded_jwt


# 生成令牌的路由函数
@app.get("/get_token")
async def get_token():
    # 准备数据
    data = {"info": "大家好我是老关。", "from": "Tony"}
    # 创建令牌
    token = create_access_token(data=data)

    return {"token": token}


# 验证令牌路由函数
@app.post("/verify_token")
async def verify_token(token: str):
    try:
        # 解码客户端提供的令牌
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        return payload
    except JWTError:
        raise HTTPException(status_code=401, detail="无法验证签名")


if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
